<?php
	class SingleSignOn 
	{
		var $loginErrorCode = "";
		var $URLonOK = "";
		var $PIDonOK = "";
		var $SessionInfo = 		array (
			'session_key'	=> "",
			'username'   	=> "",
			'accessed'   	=> "",
			'created'  		=> "",
			'fullname'  	=> "",
			'error'  		=> "",
			'temppass'      => "");
			
	function SingleSignOn()
	{
	}
	
	function handleLoginError() {
		$this->TranslateURLParams();
		if(isset($this->SessionInfo['error']) && $this->SessionInfo['error'] != "")  
		{
			$SSO_HTML = '<table><tr><td class="LoginErrorBackground"><span class="LoginErrorText">';
			switch($this->SessionInfo['error'])
			{
				case "npnomatch":
					$SSO_HTML = $SSO_HTML . 'Your new passwords did not match. Login again using old password.';
					break;
				case "unpass":
					$SSO_HTML = $SSO_HTML . 'Username/Password combination was invalid. Please try again.';
					break;
				case "sesexp":
					$SSO_HTML = $SSO_HTML . 'Your session has expired due to inactivity. Please sign in again.';
					break;
				case "nouserpass":
					$SSO_HTML = $SSO_HTML . 'Your username and/or password was left blank. Please try again.';
					break;
				case "userne":
					$SSO_HTML = $SSO_HTML . 'This username does not exist. If you believe this to be an error please contact the administrator.';
					break;
				default:
					break;
			}
			return $SSO_HTML.'<br></span></td></tr></table>';
		}
	}
	
	function createLoginPrompt($successDestination) {
		$this->TranslateURLParams();
		if($successDestination != "") {
			if(is_numeric($successDestination)) {
				$successDestination = $this->getURLfromPID($successDestination);
			}
			$this->URLonOK = $successDestination;			
		}
		
		$RequestURI = $_SERVER['REQUEST_URI'];
		//strip the error message off of the url if present
		$RequestURI = ereg_replace("error=.*(\&)?","", $RequestURI);
		
		//handle temporary password assignments
		if(isset($this->SessionInfo['error']) && $this->SessionInfo['error'] == "temppass")
		{
			$user = new user;			
			if($user->getTemporaryPassword($this->SessionInfo['username']) == $this->SessionInfo['temppass']) {	
			 	$this->SessionInfo['error'] = "";

				$SSO_HTML .= '<table> 
				<tr><td class="LoginBox"><form action="' . $RequestURI . '" method="post" STYLE="margin:0;padding:0" name="loginform">';
				$SSO_HTML .= '<span class="LoginTextReg">Either your password has expired or this is your first login.<br> Please enter your new or permanent password twice.<br><br></span>';
				$SSO_HTML .= '<span class="LoginTextReg">Username<br><input readonly="true" type="text" size="22" name="txtUsername" class="LoginTextReg" value="'.$this->SessionInfo['username'].'"><br>
				New Password<br><input class="LoginTextReg" type="password" name="txtNewPassword1" size="22"><br>Confirm<br><input class="LoginTextReg" type="password" name="txtNewPassword2" size="22"><br><input type="submit" value="Login" class="LoginButton" tabindex="3"></span>';
				$SSO_HTML .= '</form></td></tr></table><script type="text/javascript">document.forms.loginform.txtNewPassword1.focus();</script>';
			}
			else {
				$SSO_HTML = "Error.  Temporary Password Mismatch.";
			}
			
			return $SSO_HTML;
		}
		else if((!isset($_POST['txtUsername']) && !isset($_POST['txtPassword'])))
		{
			$SSO_HTML = '<table>
			<tr><td class="LoginBox"><form action="' . $RequestURI . '" method="post" style="margin:0;padding:0 0 0 0;" name="loginform">
			<table cellpadding="0" cellspacing="0" border="0"> <tr><td class="LoginTitleBackground"><span class="LoginTitle"></span></td></tr> 
			<tr><td nowrap class="LoginBodyBackground">';
			$SSO_HTML .= '<table cellpadding="0" cellspacing="0" border="0">
			<tr><td colspan="2"><span class="LoginTextReg">Username</span></td></tr>
			<tr><td colspan="2"><input type="text" size="22" name="txtUsername" class="LoginField" tabindex="1"></td></tr>
			<tr><td colspan="2"><span class="LoginTextReg">Password</span></td></tr>
			<tr><td><input type="password" size="22" name="txtPassword" class="LoginField" tabindex="2"></td>
			<td>&nbsp;&nbsp;<input type="submit" value="Login" class="LoginButton" tabindex="3"></td></tr>
			<tr><td></td></tr></table>';
			
			$SSO_HTML .= '</td></tr></table></td></tr></table></form><script type="text/javascript">document.forms.loginform.txtUsername.focus();</script>';
						
			return $SSO_HTML;
		}
		if(isset($_POST['txtUsername']) && isset($_POST['txtPassword']) && $this->SessionInfo['error'] == "")
		{
			$this->Portal_Authenticate();
		}
		if(isset($_POST['txtUsername']) && isset($_POST['txtNewPassword1']) && isset($_POST['txtNewPassword2']) && $this->SessionInfo['error'] == "")
		{
			$this->Portal_Authenticate_TempPass();
		}
	}
	
	function Portal_Authenticate_TempPass()
	{
		if($_POST['txtNewPassword1'] == $_POST['txtNewPassword2'])
		{
			global $DB;
			//create the update string 	
			$db_string = $DB->compile_db_update_string(array ('PasswordTemp' => ''));
			
			//insert the session into the sessions table
			$DB->query("UPDATE users SET " . $db_string . ", Password = SHA('" . $_POST['txtNewPassword1'] . "') "  . "WHERE Username='" . $_POST['txtUsername'] . "'");
			
			//set the password and let Portal_Authentcate take over
			$_POST['txtPassword'] = $_POST['txtNewPassword1'];
		}
		else
		{
			//setpassword and let Portal_Authentcate take over
			$_POST['txtPassword'] = "DUMMYNOVALUEBECAUSEITNEVERISSUPPOSEDTOWORK";

			$this->SessionInfo['error'] = "npnomatch";
		}
		$this->Portal_Authenticate();
	}
	
	function Portal_Authenticate()
	{
		$this->TranslateURLParams();
		// check to make sure all of the ducks are in row to authenticate
		if($this->URLonOK == "" && $this->PIDonOK == "")
		{
			die("No return address specified for login script. Contact your administrator.");
		}
		
		if($this->URLonOK != "" && $this->PIDonOK != "")
		{
			die("Both URL and PID specified for login script. Contact your administrator.");
		}
		
		if(!isset($_POST['txtUsername']))
		{
			die("No username provided to authenticate. Contact your administrator.");
		}
		if(!isset($_POST['txtPassword']))
		{
			die("No password provided to authenticate. Contact your administrator.");
		}
		//all of the ducks are "A-OK!" good to go!
		
		//store the "return on ok" address as a URL
		if($this->URLonOK != "")
		{
			$ReturnAddress = $this->URLonOK;
		}

		//store the "return on ok" address as a url with PID
		if($this->PIDonOK != "")
		{
			$ReturnAddress = 'index.php?PID=' . $this->PIDonOK;
		}
		
		//check to see if this is coming from a password reset and the passwords don't match
		if($this->SessionInfo['error'] == "npnomatch")
		{
			header('Location: ' . $ReturnAddress . '&error=npnomatch');
			exit();
		}
				
		//check to see if the username or password is blank
		if(($_POST['txtUsername'] == "")||($_POST['txtPassword'] == ""))
		{
			header('Location: ' . $ReturnAddress . '&error=nouserpass');
			exit();
		}
		
		//load the global database $DB
		global $DB;
		
		//open up a connection with the DB
		$DB->connect();
		//check to see if the username exists
		$DB->query("SELECT Username FROM users WHERE Username = '" . $_POST['txtUsername'] . "'");
		
		if($DB->get_num_rows() <= 0)
		{
			header('Location: ' . $ReturnAddress . '&error=userne');
			exit();
		}
		
		//check to see if the username and password match
		$DB->query("SELECT Username FROM users WHERE Username = '" . $_POST['txtUsername'] . "' AND Password = SHA('" . $_POST['txtPassword'] . "')");
		
		//if they don't match check to see if there is a temp password assignment and if it matches
		if($DB->get_num_rows() <= 0)
		{
			//check to see if the username and temp password match
			$DB->query("SELECT Username FROM users WHERE Username = '" . $_POST['txtUsername'] . "' AND PasswordTemp = '" . $_POST['txtPassword'] . "'");
			if($DB->get_num_rows() <= 0)
			{
				header('Location: ' . $ReturnAddress . '&error=unpass');
				exit();
			}
			else
			{				
				header('Location: ' . $ReturnAddress . '&error=temppass&username=' . $_POST['txtUsername'] . '&temppass=' . $_POST['txtPassword']);
				exit();
			}
		}
		
		$key_length = rand(35,50);
		$done = "no";
		while($done != "yes")
		{
			$session_key = "";
			for($key_index=1; $key_index <= $key_length; $key_index++)
			{
				$is_char = rand(1,100);
				if( $is_char % 2 == 1)
				{
					$next_char = rand(1,9);
				}
				else
				{
					$is_lower = rand(1,100);
					
					if($is_lower % 2 == 1)
					{
						$char_num = rand(65,90);
					}
					else
					{
						$char_num = rand(97,122);
					}
				 $next_char = chr($char_num);
				}
				$session_key = $session_key . $next_char;
			}
			
			//check to see if that key already exists
			$DB->query("SELECT session_key FROM sessions WHERE session_key = '" . $session_key. "'" );
			
			//it does not exist 
			if($DB->get_num_rows() <= 0)
			{
				$done = "yes";
			}
			//it does exits, wow!  what are the chances?
			if($DB->get_num_rows() > 0)
			{
				$done = "no";
			}
		}
		
		//get the current date and format it for mySQL datetime
		$date = getDate();
		foreach($date as $item=>$value) 
		{
			 if ($value < 10)
					 $date[$item] = "0".$value;
		}
		$SQLdate = $date['year']."-".$date['mon']."-".$date['mday']." ".$date['hours'].":".$date['minutes'].":".$date['seconds'];
	
		//create the insert string 	
		$db_string = $DB->compile_db_insert_string( 
		array (
			'session_key'		=> $session_key,
			'username'   		=> $_POST['txtUsername'],
			'created'    		=> $SQLdate,
			'accessed'  		=> $SQLdate)
			);
		
		//insert the session into the sessions table
		$DB->query("INSERT INTO sessions (".$db_string['FIELD_NAMES'].") VALUES (".$db_string['FIELD_VALUES'].")");
		
		//login successful clear any residual error message and go to the URL or PID specified
		$this->SessionInfo['error'] = "";
		header('Location: ' . $ReturnAddress . '&session_key=' . $session_key);
		exit();
	}
	
	function getSessionInformation()	{
		$this->TranslateURLParams();
		//if the session_key just came from the url
		if(isset($_GET['session_key']) && $_GET['session_key'] != "")
		{	
			setcookie("session_key", $this->SessionInfo['session_key'],false,"/");
		} 
		//if the contents of the session_key has been saved as a cookie restore it to this object
		elseif(isset($_COOKIE['session_key']) && $_COOKIE['session_key'] != "")
		{
			$this->SessionInfo['session_key'] = $_COOKIE['session_key'];
		}
		//if the cookie and the get do not contain a session_key then there is no session to validate
		else 
		{
			$this->SessionInfo['session_key'] = "";
		}
		
		//load the global database $DB
		global $DB;
		//open up a connection with the DB
		$DB->connect();
		//find the session if it exists and is not expired
		$DB->query("SELECT *, (UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(accessed))/60 AS MinutesGoneBy FROM sessions WHERE  ((UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(accessed))/60) < 60 AND session_key = '" . $this->SessionInfo['session_key'] . "'");
		
		//if there is no un-expired session, make sure there is not an old one out there which need to be deleted
		if($DB->get_num_rows() <= 0)
		{
			$DB->query("DELETE FROM sessions WHERE session_key='" . $this->SessionInfo['session_key'] . "'");
			if($DB->get_affected_rows() > 0)
			{
				$this->SessionInfo['error'] = "sesexp";			
				return $this->SessionInfo;		
			}
			else 
			{
				return $this->SessionInfo;
			}
		}
		
		//grab the row from the table
		$row = $DB->fetch_row();
		
		//Fill the SessionInfo[] array
		$this->SessionInfo['username'] = $row['username'];
		$this->SessionInfo['accessed'] = $row['accessed'];
		$this->SessionInfo['created'] = $row['created'];
		$this->SessionInfo['session_key'] = $row['session_key'];
		$this->SessionInfo['fullname'] = $this->GetFullName($this->SessionInfo['username']);

		//get the current date and format it for mySQL datetime
		$date = getDate();
		foreach($date as $item=>$value) 
		{
			 if ($value < 10)
					 $date[$item] = "0".$value;
		}
		$SQLdate = $date['year']."-".$date['mon']."-".$date['mday']." ".$date['hours'].":".$date['minutes'].":".$date['seconds'];

		//create the update string 	
		$db_string = $DB->compile_db_update_string(array ('accessed' => $SQLdate));
		
		//insert the session into the sessions table
		$DB->query("UPDATE sessions SET " . $db_string . "WHERE session_key='" . $this->SessionInfo['session_key'] . "'");
		
		return $this->SessionInfo;		
	}
	
	function TranslateURLParams()
	{
		if(isset($_GET['error']))
		{
				if(isset($_GET['temppass']) && isset($_GET['username'])) {
					$this->SessionInfo['temppass'] = $_GET['temppass'];
					$this->SessionInfo['username'] = $_GET['username'];
				}
			$this->SessionInfo['error'] = $_GET['error'];
		}
		if(isset($_GET['session_key']))
		{
			$this->SessionInfo['session_key'] = $_GET['session_key'];
		}
	}
	
	function GetFullName($username)
	{
		if($username != "")
		{
			//load the global database $DB
			global $DB;
			//open up a connection with the DB
			$DB->connect();
			//find the session if it exists and is not expired
			$DB->query("SELECT FirstName, CONCAT(LEFT(MiddleName, 1), '.') AS MiddleInit, LastName FROM users WHERE username='" . $username . "'");
			//grab the row from the table
			$row = $DB->fetch_row();
			//build the FullName
			if($row['FirstName'] != "")
			{
				$FullName = $row['FirstName'];
			}
			if($row['MiddleInit'] != ".")
			{
				$FullName = $FullName . " " . $row['MiddleInit'];
			}
			if($row['LastName'] != "")
			{
				$FullName = $FullName . " " . $row['LastName'];
			}
		}
		else
		{
			$FullName = "";
		}

		return $FullName; 				
	}
	
	function isValidSession($TransferURL, $SessionInfo)
	{
		if(isset($SessionInfo['error']) && $SessionInfo['error'] != "")
		{
			if(isset($SessionInfo['temppass']) && isset($SessionInfo['username'])) {
				header("Location:" . $TransferURL . "&error=" . $SessionInfo['error']."&username=".$SessionInfo['username']."&temppass=".$SessionInfo['temppass']);
			}
			else {
				header("Location:" . $TransferURL . "&error=" . $SessionInfo['error']);
			}
			exit();
		}
		if($SessionInfo['username'] == "")
		{
			header("Location: " . $TransferURL);
			exit();
		}
		return $SessionInfo;
	}
	
	function CheckUserExists($username)
	{
		global $DB;
		$DB->query("SELECT * FROM users WHERE username = '" . $username . "'");
		if($DB->get_num_rows() > 0)
		{
			return true;
		}
		else
		{
			return false;
		}
	}

	function GetTakenLikeUsers($username)
	{
		global $DB;
		$DB->query("SELECT * FROM users WHERE username LIKE '%" . $username . "%'");
		$array_of_users = ""; 
		$array_index = 0;
		while($row = $DB->fetch_row())
		{
			$array_of_users[$array_index] = $row['Username'];
			$array_index++;
		}
		
		return $array_of_users;
	}
	
	function getURLfromPID($PID) {
		return "http://localhost/index.php?PID=" . $PID;
	}

	function resetPassword($email){
		global $DB;
		$DB->query("select username, firstname, lastname, passwordtemp from lwbc_main.users where email ='".$email."'");
				
		if($row=$DB->fetch_row()) {
			$new_temp_pass = str_shuffle($row['lastname'] . $row['firstname']);		
			$DB->query("update users set passwordtemp ='" . $new_temp_pass . "', password='' where username='" . $row['username'] . "'");
			
			return $new_temp_pass;
		}
		
	}
	
	function sendTemporaryPasswordEmail($username,$temporaryPassword,$email,$fullName) {
		$emailText = $fullName . "," .
		"\n\r\nYour username is   " . $username .
		"\nYour temporary password is   " . $temporaryPassword . "  (use this the first time you login) " . 
		"\r\nYou'll be able to setup your permanent password the first time you login." .
		"\r\nYour account gives you access to a variety of Living Word Online tools.  You can access them at http://www.lwbc.net/LWOnline" .
		"\r\n\r\nLiving Word Online Team" .
		"\nadmin@lwbc.net" .
		"\n(434)525-7736";
		if(mail($email ,"Living Word Online Account",$emailText,"From: Living Word Baptist Church <admin@lwbc.net>" . "\r\n" . "Reply-To: admin@lwbc.net")) {
			return true;
		}
		else {
			return false;
		}
	}
}	
?>
